package groupManagement;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;

public class User {
	
	private static HashMap<String, User> users=new HashMap<String, User>();
	private String lang;
	private String name;
	private Set<ChatGroup> groups;
	private Timer timer;
	
	private User(String name,String lang){
		this.lang=lang;
		this.name=name;
		this.groups=new HashSet<ChatGroup>();
		this.timer=new Timer();
		this.timer.schedule(new UserTimer(name), 30000); //change this
		synchronized (users) {
			users.put(name,this);
			
		}
	}
	
	private void resetTimer(){
		this.timer.cancel();
		this.timer=new Timer();
		this.timer.schedule(new UserTimer(name), 30000);
	}
	
	public static void addUserToGroup(String user,String lang,ChatGroup group){
		synchronized (users) {
			if(users.containsKey(user)){
				User current=users.get(user);
				synchronized (current.groups) {
					
					if(!current.groups.contains(group)){
						current.groups.add(group);
					}
				}
				current.resetTimer();
			}
			else{
				User current=new User(user,lang);
				synchronized (current.groups) {
					
					current.groups.add(group);
				}
			}
		}
	}
	
	public static void removeUserFromGroup(String user,ChatGroup group){
		synchronized (users) {
			
			if(!users.containsKey(user)){
				return ; //user not in  records
			}
			else{
				User current = users.get(user);
				synchronized (current.groups) {
					
					current.groups.remove(group);
					if(current.groups.isEmpty()){
						current.timer.cancel();
						users.remove(user);
					}
				}
			}
		}
	}
	
	public static void userImAlive(String name){
		synchronized (users) {
			
			if(users.containsKey(name)){
				users.get(name).resetTimer();
			}
		}
	}
	
	public static void removeUser(String name){
		Set<ChatGroup> groups = new HashSet<ChatGroup>();
		synchronized (users) {
			
			if(!users.containsKey(name)){
				return;
			}
			User current=users.get(name);
			current.timer.cancel();
			synchronized (current.groups) {
				groups.addAll(current.groups);
				users.remove(name);
			}
		}
		for(ChatGroup group : groups){
			group.removeUser(name);
		}
	}
	
	public static void printUser(String userName){
		synchronized (users) {
			
			if(users.containsKey(userName)){
				User current=users.get(userName);
				System.out.println("User name: " + current.name);
				System.out.println("User language: " + current.lang);
			}
		}
	}
}
